package com.xoa.plugin.workflow.workflowservice.imlp.lnsfplugin;

import com.xoa.dao.WFE.WFEFlowProcessMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.work.WorkMapper;
import com.xoa.dao.workflow.FlowFormTypeMapper;
import com.xoa.dao.workflow.FlowTypeModelMapper;
import com.xoa.dev.efficiency.dao.FlowAbilityMonitorMapper;
import com.xoa.dev.efficiency.dao.FlowParaMapper;
import com.xoa.dev.efficiency.model.FlowAbilityMonitor;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowFormType;
import com.xoa.model.workflow.FlowProcess;
import com.xoa.model.workflow.FlowTypeModel;
import com.xoa.model.workflow.TriggerPlugIn;
import com.xoa.util.CookiesUtil;
import com.xoa.util.SpringTool;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @创建作者:李然  Lr
* @方法描述：工具类
* @创建时间：16:03 2019/5/20
**/
@Service
public class LnsfUtil {

    private static LnsfUtil lnsfUtil;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private FlowParaMapper flowParaMapper;

    @Autowired
    private WFEFlowProcessMapper wfeFlowProcessMapper;

    @Autowired
    private FlowAbilityMonitorMapper flowAbilityMonitorMapper;
    @Autowired
    private WorkMapper workMapper;
    @Autowired
    private FlowTypeModelMapper flowTypeModelMapper;
    @Autowired
    private FlowFormTypeMapper flowFormTypeMapper;
    @Autowired
    private UsersMapper usersMapper;

    //获取工作办理时限，如果没有，则返回null；
    public String getWorkDeadline(String flowId, Integer prcsId) {
        FlowProcess flowProcess = wfeFlowProcessMapper.findProcess(Integer.parseInt(flowId), prcsId);
        String timeOut = null;
        if (flowProcess != null) {
            //赋值
            timeOut = flowProcess.getTimeOut();
        }
        //当前时间加上办理时限再转化为时间格式
        if (timeOut != null && !timeOut.equals("")) {
            long atDateInt = new Date().getTime();
            long banlishixian = atDateInt + Integer.parseInt(timeOut) * 60 * 60 * 1000;
            return sdf.format(new Date(banlishixian));
        }
        return null;
    }

    //查找第一步办理记录
    public String selectOnePrcsTime(Map map) {
        //为了防止查出多条的可能，用list接收
        List<String> prcsTimes = flowAbilityMonitorMapper.getPrcsTimeByMap(map);
        if (prcsTimes != null && prcsTimes.size() > 0) {
            String prcsTime=prcsTimes.get(0);
            if(prcsTimes.get(0).contains(".")){
                prcsTime=prcsTimes.get(0).split("\\.")[0];
            }
            return prcsTime;
        }
        return null;
    }

    /**
     * 统一获取当前登陆用户
     */
    public  Users getUser(HttpServletRequest  request){
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        return user;
    }

    /**
     * @创建作者:李然 Lr
     * @方法描述：返回具体字段，data_xx
     * @创建时间：10:08 2018/8/20
     **/
    public String getCustomData(Document document, String str) {
        Elements elements = document.select("[title=" + str + "]");
        String name = null;
        if (elements.size() > 0) {
            name = elements.get(0).attr("name");
        }
        return name;
    }
    //因频繁调用，添加一个返回工作名称方法
    public String getWorkData(Map<String,Object> mapParam) {
        String flowId=(String) mapParam.get("flowId");
        String runId=(String) mapParam.get("runId");
        String tableName="flow_data_"+flowId;
        Map map=new HashMap();
        map.put("tableName",tableName);
        map.put("runId",runId);
        Map mapData=workMapper.select(map);
        String title=(String) mapParam.get("title");
        Document document=getDocument(Integer.parseInt(flowId));
        String value=String.valueOf(getCustomData(document,title));
        Object o=mapData.get(value);
        String result=null;
        if(o==null){
            String lowerCase=value.toLowerCase();
            Object oLowe=mapData.get(lowerCase);
            if(oLowe==null){
                String upperCase=value.toUpperCase();
                Object oUpper=mapData.get(upperCase);
                result=String.valueOf(oUpper);
            }else{
                result=String.valueOf(oLowe);
            }
        }
        return result;
    }

    //升级mapget方法
    public String mapGet(Map<String,String>map, String str){
        String value=map.get(str);
        if(str!=null&&!str.equals("")) {
            if (value == null) {
                str = str.toLowerCase();
                value = map.get(str);
                if (value == null) {
                    str = str.toUpperCase();
                    value = map.get(str);
                }
            }
        }
        if(value!=null){
            if(value.contains("|")){
                String[] renyuans=value.split("\\|");
                String renyuan=renyuans[1];
                if(renyuan.contains(",")){
                    value=renyuan.split(",")[0];
                }
            }
        }
        return value;
    }

    //分割字符串，获取key value，存入map
    public Map<String, String> toMap(String json) {
        Map<String, String> map = new HashMap<String, String>();
        //判断json的格式
        if (json.charAt(0) == '[') {
            String zhuanString = json.substring(1, json.length() - 1);
            zhuanString = zhuanString.replaceAll("\\{", "");
            //得到key  value  集合
            String[] jsonArray = zhuanString.split("\\},");
            //遍历得到每一组
            for (int i = 0; i < jsonArray.length; i++) {
                //分割，得到key与value
                String[] keyValue = jsonArray[i].split(",");
                String key = quChuMaoHao((keyValue[0].split(":"))[1]);
                String value = quChuMaoHao((keyValue[1].split(":"))[1]);
                if (value != null && !value.equals("") && !value.equals("}")) {
                    map.put(key, value);
                }
            }
        } else if (json.charAt(0) == '{') {
            String zhuanString = json.substring(1, json.length() - 1);
            String[] jsonArray = zhuanString.split(",");
            //遍历分割开后的数组
            for (int i = 0; i < jsonArray.length; i++) {
                //通过分割：得到键和值
                String[] keyValue = jsonArray[i].split(":");
                //判断一下键与值是否被""包裹，如果有，则取出
                String key = quChuMaoHao(keyValue[0]);
                String value = quChuMaoHao(keyValue[1]);
                map.put(key, value);
            }

        }

        return map;
    }

    //判断字符串是否被冒号包裹，如果有则去除
    public  String quChuMaoHao(String s) {
        if (s != null && !s.equals("")) {
            if (s.contains("\"")) {
                s = s.replaceAll("\"", "");
            }
        }
        return s;
    }

    public static LnsfUtil init(){
        if (lnsfUtil==null){
            lnsfUtil=(LnsfUtil) SpringTool.getBean("lnsfUtil");
        }
        return lnsfUtil;
    }

    /**
     * 获取doc对象
     * @param flowId
     * @return
     */
    public Document getDocument(Integer flowId){
        FlowTypeModel flowTypeModel = flowTypeModelMapper.queryOneObject(flowId);
        //表单
        FlowFormType flowFormType = flowFormTypeMapper.qureyItemMax(flowTypeModel.getFormId());
        //解析表单
        Document document = getField(flowFormType.getPrintModel());
        return document;
    }

    //解析
    public Document getField(String printModel) {
        Document document = null;
        //解析html
        document = Jsoup.parse(printModel);
        return document;
    }

    //插入或者修改重点工作表
    public Integer setData(FlowAbilityMonitor flowAbilityMonitor) {
        Integer result = null;
        //查询是否有此纪录
        Integer id = flowAbilityMonitorMapper.getIdByFlowAbilityMonitor(flowAbilityMonitor);
        flowAbilityMonitor.setId(id);
        //如果没有则插入
        if (id == null) {
            result = flowAbilityMonitorMapper.insertSelective(flowAbilityMonitor);
        }
        //有则修改
        else {
            result = flowAbilityMonitorMapper.updateByPrimaryKeySelective(flowAbilityMonitor);
        }
        return result;
    }

    //根据姓名获取userId和部门Id
    public Map<String,String> getIds(String name){
        Map<String,String> resultMap=new HashMap<>();
        Map<String,Object> userIdAndDeptId=flowAbilityMonitorMapper.getUserIdAndDeptIdByName(name);
        String userId=userIdAndDeptId.get("USER_ID").toString();
        String deptId=userIdAndDeptId.get("DEPT_ID").toString();
        resultMap.put("USER_ID",userId);
        resultMap.put("DEPT_ID",deptId);
        return resultMap;
    }

    //获取表单title对应的值
    public String getWorkNameValue(String flowId,String runId,String name){
        Map map1=new HashMap();
        map1.put("runId",runId);
        map1.put("flowId",flowId);
        map1.put("title",name);
        String workName=getWorkData(map1);
        if(StringUtils.checkNull(workName)){
            workName=null;
        }
        return workName;
    }

    public List<String[]> getdubanyijian(String str) {
        if (str != null) {
            String dubanyijian = str;
            if (dubanyijian.charAt(0) == '[' && dubanyijian.charAt(1) == '[') {
                dubanyijian = dubanyijian.substring(1, dubanyijian.length() - 1);
            }

            String[] dubanyijians = dubanyijian.split("\\|");
            if (dubanyijians != null) {
                String dubanyijianStr = dubanyijians[0];
                String[] yijian = dubanyijianStr.split("\r\n");
                if (yijian != null) {
                    List<String[]> yijianList = new ArrayList<>();
                    for (int i = 0; i < yijian.length; i++) {
                        String[] ziduan = yijian[i].split("\\`");
                        if(ziduan!=null&&!ziduan.equals("")) {
                            yijianList.add(ziduan);
                        }
                    }
                    if (yijianList.size() > 0) {
                        return yijianList;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 根据传入的主办人,返回主办人数组
     * @param nextUser
     * @return
     */
    public String[] getPrcsOpUser(String nextUser){
        if(nextUser!=null&&nextUser.contains(",")){
            String[] prcsOpUser=nextUser.split(",");
            return prcsOpUser;
        }else{
            String[] result={nextUser};
            return result;
        }
    }


    public SimpleDateFormat getSdf() {
        return sdf;
    }

    public FlowParaMapper getFlowParaMapper() {
        return flowParaMapper;
    }

    public WFEFlowProcessMapper getWfeFlowProcessMapper() {
        return wfeFlowProcessMapper;
    }

    public FlowAbilityMonitorMapper getFlowAbilityMonitorMapper() {
        return flowAbilityMonitorMapper;
    }

    public WorkMapper getWorkMapper() {
        return workMapper;
    }

    public FlowTypeModelMapper getFlowTypeModelMapper() {
        return flowTypeModelMapper;
    }

    public FlowFormTypeMapper getFlowFormTypeMapper() {
        return flowFormTypeMapper;
    }

    public UsersMapper getUsersMapper() {
        return usersMapper;
    }
}
